<template>
  <el-upload class="avatar-uploader" :action="uploadConfig.actionURL"
    accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.GIF,.BMP" :show-file-list="false" :on-success="handleAvatarSuccess1"
    :on-error="handleUploadError" :data="uploadConfig.tokens" :headers="uploadConfig.headers"
    :before-upload="beforeAvatarUpload1">
    <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon" v-loading="pictureUploading"></i>
  </el-upload>
</template>
<script>
import ossBaseUrl from "@/ossconfig/index";
import { admingetoss } from "@/api/index";
import qs from "qs";
export default {
  props: ["isimgurl"],
  data() {
    return {
      maxSize: 20 * 1048576,
      ruleForm: {},
      uploadConfig: {
        actionURL: ossBaseUrl,
        headers: {},
        tokens: {},
        dir: "",
      },
      pictureUploading: false,
    };
  },
  activated() { },
  watch: {
    isimgurl() {
      this.$set(this.ruleForm, "imgUrl", this.isimgurl);
    },
  },
  created() {
    this.$set(this.ruleForm, "imgUrl", this.isimgurl);
  },
  mounted() { },
  methods: {
    handleAvatarSuccess1(res, file) {
      const url = this.setImg(file);
      this.$emit("imgsuccess", url);
      this.$set(this.ruleForm, "imgUrl", url);
      console.log(this.ruleForm.imgUrl);
      this.pictureUploading = false;
    },
    handleUploadError() {
      this.pictureUploading = false;
      this.$message.error("上传失败！请稍后再试！");
    },
    setImg(file) {
      const arr = file.name.split(".");
      const un_name = `${file.uid}.${arr[arr.length - 1]}`;
      var fileAddress = this.uploadConfig.dir + un_name;
      return this.uploadConfig.actionURL + fileAddress;
    },
    showSize(size) {
      let data = "";
      if (size < 1048576) {
        data = Number((size / 1024).toFixed(2)) + "KB";
      } else if (size === 1048576) {
        data = "1MB";
      } else if (size > 1048576 && size < 1073741824) {
        data = Number((size / (1024 * 1024)).toFixed(2)) + "MB";
      } else if (size > 1048576 && size === 1073741824) {
        data = "1GB";
      } else if (size > 1073741824 && size < 1099511627776) {
        data = Number((size / (1024 * 1024 * 1024)).toFixed(2)) + "GB";
      } else {
        data = "1TB以及以上";
      }
      return data;
    },
    beforeAvatarUpload1(file) {
      this.fileSize = file.size;
      const isBeyond = file.size < this.maxSize;
      if (!isBeyond) {
        const beyondTip =
          "文件大小超过" + this.showSize(this.maxSize) + ",请重新上传。";
        this.$message.error(beyondTip);
        return isBeyond;
      } else {
        const arr = file.name.split(".");
        const un_name = `${file.uid}.${arr[arr.length - 1]}`;
        this.pictureUploading = true;
        return this.generateTokens(un_name, file);
      }

      // let base = URL.createObjectURL(file);
      // console.log(file);
      // this.ruleForm.imgUrl = base;
      // console.log(base);
    },
    generateTokens(key, file) {
      return new Promise(
        (resolve, reject) => {
          // 先这样处理
          admingetoss({
            type: 0,
          }).then((response) => {
            const { data } = response;
            if (!data) {
              this.$message.error("获取阿里云配置失败！请稍后再试！");
            }
            file.startTime = new Date().getTime();
            const dir = data.dir;
            this.uploadConfig.dir = dir;
            this.uploadConfig.tokens.key = dir + key;
            this.uploadConfig.tokens.policy = data.encodedPolicy;
            this.uploadConfig.tokens.OSSAccessKeyId = data.accessKeyId;
            this.uploadConfig.tokens.success_action_status = "200";
            this.uploadConfig.tokens.signature = data.postSignature;
            if (data.host) {
              this.uploadConfig.actionURL = data.host;
            }
            resolve(true);
          });
        },
        () => {
          // eslint-disable-next-line no-undef
          reject(false);
        }
      );
    },
  },
};
</script>
<style lang='scss' scoped>
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.avatar-uploader ::v-deep .el-upload {
  // border: 1px solid #e5e5e5;
  border-radius: 5px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #ff5478;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px solid #e5e5e5;
  border-radius: 5px;
}
</style>
